本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (20) 建立購物車系統 - 3
在CartApi專案的資料夾Controllers,新增CartController類別且繼承ControllerBase,此類別是購物車系統的Http Api,之後要讓WebMvc呼叫。Action包含對購物車的更新、取得與刪除,需依靠注入的CartRepository物件。
using CartApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Threading.Tasks;
namespace CartApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CartController : ControllerBase
{
private readonly ILogger<CartController> _logger;
private readonly ICartRepository _repository;
public CartController(ILogger<CartController> logger, ICartRepository repository)
{
_logger = logger;
_repository = repository;
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(Cart), (int)HttpStatusCode.OK)]
public async Task<IActionResult> Get(string id)
{
var basket = await _repository.GetCartAsync(id);
return Ok(basket);
}
[HttpPost]
[ProducesResponseType(typeof(Cart), (int)HttpStatusCode.OK)]
public async Task<IActionResult> Post([FromBody] Cart value)
{
var basket = await _repository.UpdateCartAsync(value);
return Ok(basket);
}
[HttpDelete("{id}")]
public void Delete(string id)
{
_repository.DeleteCartAsync(id);
}
}
}
在Startup.cs,註冊所需的Redis、Repository服務。在AddControllers需要在Filters增加之前寫的HttpGlobalExceptionFilter功能,並且要安裝Microsoft.AspNetCore.Mvc.NewtonsoftJson,才能用AddNewtonsoftJson的功能,使Json不檢查自我參考的迴圈問題。Redis ConnectionMultiplexer註冊的是單例模式,不用每次都新增連線物件。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddNewtonsoftJson(options => {
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.Configure<CartSettings>(Configuration);
services.AddSingleton<ConnectionMultiplexer>(sp =>
{
var settings = sp.GetRequiredService<IOptions<CartSettings>>().Value;
var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);
configuration.ResolveDns = true;
configuration.AbortOnConnectFail = false;
return ConnectionMultiplexer.Connect(configuration);
});
services.AddTransient<ICartRepository, CartRepository>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
-----------------------------------------------------
之後再來寫Docker啟用Redis和使用Swagger測試CartController